package com.example.quizamination.adapters

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.BaseAdapter
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import com.example.quizamination.R
import com.example.quizamination.quiz.Question

class QuestionsAdapter(
    val context: Context, val questions: List<Question>, val answers: MutableList<Int>
) : BaseAdapter() {
    val layoutInflater: LayoutInflater

    init {
        this.layoutInflater = LayoutInflater.from(context)
    }

    override fun getCount(): Int {
        return questions.size
    }

    override fun getItem(position: Int): Any {
        return questions[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View = layoutInflater.inflate(R.layout.activity_questions_list_view_item, null)
        val radioGroup: RadioGroup = view.findViewById(R.id.questionRadioGroup)
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            val answerIndex: Int = group.indexOfChild(group.findViewById(checkedId)) - 1
            val questionIndex = group.tag as Int
            answers[questionIndex] = answerIndex
        }
        radioGroup.tag = position
        val textView: TextView = view.findViewById(R.id.questionTextView)
        val firstAnswer: RadioButton = view.findViewById(R.id.firstAnswer)
        val secondAnswer: RadioButton = view.findViewById(R.id.secondAnswer)
        val thirdAnswer: RadioButton = view.findViewById(R.id.thirdAnswer)
        val fourthAnswer: RadioButton = view.findViewById(R.id.fourthAnswer)

        textView.setTextAppearance(R.style.Question)
        textView.text = questions[position].question
        firstAnswer.text = questions[position].answers[0]
        secondAnswer.text = questions[position].answers[1]
        thirdAnswer.text = questions[position].answers[2]
        fourthAnswer.text = questions[position].answers[3]

        val fadeIn = AnimationUtils.loadAnimation(context, R.anim.fade_in)
        radioGroup.startAnimation(fadeIn)

        return view
    }
}